package edu.pku.sei.act.actools.util.policy;

import java.util.ArrayList;

import edu.pku.sei.act.actools.util.env.ObjectProxy;


public abstract class ObjectAdapter {
	protected ObjectContext context;
	protected String NodeID;
	protected String ObjectID;
	protected Object owner;
	protected String state;
	protected ArrayList<OBPolicy> policySet;
	public ObjectAdapter(String NodeID, String ObjectID, Object owner) {
		this.NodeID = NodeID;
		this.ObjectID = ObjectID;
		this.owner = owner;
	}
	public void subscribe(String template) {
		context.envEntry.subscribe(getProxy(), template, -1);
	}
	public void acquire(String template) {
		context.envEntry.acquire(getProxy(), template, -1);
	}
	public void write(String tuple, String type, long leaseTime) {
		context.envEntry.Write(getProxy(),tuple, type, leaseTime);
	}
	public String toString() {
		return NodeID + "^" + ObjectID;
	}
	public String getOwnerInfo() {
		return toString();
	}
	public ObjectProxy getProxy() {
		return new ObjectProxy(getOwnerInfo());
	}
	public void setState(String state) {
		this.state = state;
		for(int i = 0; i < policySet.size(); i++) {
			if(policySet.get(i).preCondition == state) {
				policySet.get(i).enable();
				if(policySet.get(i).triggerEvent == null)
					policySet.get(i).fire();
				else {
					if(policySet.get(i).triggerEvent.type == TaskEvent.MONO_MSG)
						acquire(policySet.get(i).triggerEvent.toTemplate());
					else
						subscribe(policySet.get(i).triggerEvent.toTemplate());
				}
			}
			else
				policySet.get(i).disable();
		}
	}
}
